<?php
/**
 * @property Job $Job
 * @property SessionComponent $Session
 */
class JobsController extends AppController {

	var $name = 'Jobs';
	var $helpers = array('Js', 'MyForm');
  
  var $tagDelimiter = ","; // separator to use in the input form (form controller will 'explode' on this).

  /**
   * INDEX
   */
	function index() {
    
		$this->Job->recursive = 0;
    //$this->Job->recursive = -1; // just experimenting
		$this->set('jobs', $this->paginate());
	}

  /**
   * VIEW
   */
	function view($id = null) {
    
		if (!$id) {
			$this->Session->setFlash(__('Invalid job', true));
			$this->redirect(array('action' => 'index'));
		}
    
    $jobVersions = $this->Job->JobVersion->find('all', array('conditions'=>array('JobVersion.job_id'=>$id)));
    
    $this->set('jobVersions', $jobVersions);
		$this->set('job', $this->Job->read(null, $id));
    
    //debug($id);
    //debug($jobVersions);
	} /////////// end view() //////////////////////////////////////

  /**
   * ADD
   */
	function add() {

    ////////////////////////////////////////
    /////// When saving new data ///////////
    if (!empty($this->data)) {
      //debug($this->data);
      
      // If no Alt Name provided, don't save to it's table
      if( empty($this->data['JobAltName']['name'])) {
        //debug("Looks like this->data['JobAltName']['name'] is EMPTY!");
        unset ($this->data['JobAltName']); // now saveAll(this->data) won't try saving in job_alt_names table
      }
      // If no Description provided, don't save to it's table
      if( empty($this->data['Description']['content'])) {
        //debug("Looks like this->data['Description']['content'] is EMPTY!");
        unset ($this->data['Description']); // now saveAll(this->data) won't try saving in descriptions table
      }
            
			$this->Job->create();
			
      if ($this->Job->saveAll($this->data, array('validate'=>'first'))) {
				
        $this->Session->setFlash(__('The job has been saved', true));
				$this->redirect(array('action' => 'index'));
			} 
      else {
				$this->Session->setFlash(__('The job could not be saved. Please, try again.', true));
			}
		}
    
    ////////////////////////////////////////////////
    ////////// When accessing new add page /////////
    
		//$jobTypes = $this->Job->JobType->find('list');

		$tags = $this->Job->Tag->find('list');

    //$this->set(compact('jobTypes'));
    
	} //////////////////  end add() ///////////////////////////////////

  /**
   * EDIT
   */
	function edit($id = null) {
    // If Invalid (no id provided and no data sent)
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid job', true));
			$this->redirect(array('action' => 'index'));
		}
    
    // If ready to save data
		if (!empty($this->data)) {
        // <editor-fold defaultstate="collapsed" desc="Handle updating/deleting Job Alt Name">
      // HANDLE ALT NAME
      // If no Alt Name provided AND the edited record originally HAD an Alt Name
      // to begin with, then DELETE the old Alt Name from it's table 
      // and prevent saving this blank replacement.
      if( empty($this->data['JobAltName']['name']) && 
          is_numeric($this->data['JobAltName']['id']) ) { // a numeric id field included if the record had an id to begin with
        
        // Delete the Alt Name
        if ($this->Job->JobAltName->delete($this->data['JobAltName']['id'])) {
          $this->Session->setFlash(__('Job alt name deleted', true));
        }
        else {
          $this->Session->setFlash(__('Job alt name was not deleted', true));
        }
        unset ($this->data['JobAltName']); // now saveAll(this->data) won't try saving in job_alt_names table
      }
      // If no Alt Name provided AND the edited record didn't have an Alt Name to begin with,
      //  then don't save to it's table (and don't try to delete).
      else if( empty($this->data['JobAltName']['name']) ) {
        //debug("Looks like this->data['JobAltName']['name'] is EMPTY!");
        unset ($this->data['JobAltName']); // now saveAll(this->data) won't try saving in job_alt_names table
      } // </editor-fold>
      
        // <editor-fold defaultstate="collapsed" desc="Handle updating/deleting Description">
      // HANDLE DESCRIPTIONS (same issues as with Alt Name above)
      if (empty($this->data['Description']['content']) &&
              is_numeric($this->data['Description']['id'])) {
        // Delete the Description
        if ($this->Job->Description->delete($this->data['Description']['id'])) {
          $this->Session->setFlash(__('Descripotion deleted', true));
        }         else {
          $this->Session->setFlash(__('Descripotion was not deleted', true));
        }

        unset($this->data['Description']); // now saveAll(this->data) won't try saving in descriptions table
      }
      // If no Description provided and there never was one, don't save to it's table
      else if (empty($this->data['Description']['content'])) {
        unset($this->data['Description']); // now saveAll(this->data) won't try saving in descriptions table
      }// </editor-fold>
            
      
      // Save All
      if ($this->Job->saveAll($this->data, array('validate'=>'first'))) {
				$this->Session->setFlash(__('The job has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The job could not be saved. Please, try again.', true));
			}
		}
    ///////////////////////////////////////////////////////////////
    ////// When accessing new edit page ///////////////////////////
		if (empty($this->data)) {
			$this->data = $this->Job->read(null, $id);
		}

    // these queries not working right... deal with it later/elsewhere.
        //$tag_ids = $this->Job->JobsTag->find('list', array('condiditions'=>array('JobsTag.job_id'=>$id),
        //                                                   'fields'      =>array('JobsTag.tag_id'     )));
        //$tags = $this->Job->JobsTag->Tag->find('list', array('conditions'=>array('Tag.id'=>$tag_ids)));

                                                    

    $this->set(compact('jobTypes', 'tags'));
    
	} //////////////// end edit() ////////////////////////////////

  /**
   * FORM()   Acts as the controller action for both Adding a new Job,
   *          as well as adding a new Job Version to an existing Job.  It will perhaps also be
   *          the controller action for editing existing Jobs or JobVersions.
   * 
   * @param $job_id                Possible values: "new" (for brand new Job), or an existing
   *                                                     Job's id.
   * @param $template_version_id   The id of the JobVersion to use as a template for the parameter
   *                               values for a new JobVersion. 
   *                               Possible values: "new" (just use default vals), or an existing
   *                               JobVersion's id.
   * @param $edit_job_id           If provided, then the user wants to edit an existing Job.
   *                               Note that this option only lets the user edit the Job fields, and not
   *                               any JobVersion fields. If this parameter if passed, $edit_version_id will
   *                               be ignored.
   * @param $edit_version_id       If provided, then the user wants to edit an existing JobVersion,
   *                               and that version will be used to populate form fields 
   *                               ($template_version_id would be ignored).
   *                               Note that if the JobVersion has already been processed, we are probably
   *                               only going to the let the user edit certain JobVersion metadata fields,
   *                               and not any processing parameters. This is because once a job has been 
   *                               processed, it doesn't make sense to be able to change the parameters that
   *                               were used - you can't re-write history!
   */
  function form($job_id = 'new', $template_version_id = 'new', $edit_job_id = null, $edit_version_id = null ) {
     
    // Show values of params
    debug($job_id);  debug($template_version_id); debug($edit_job_id);  debug($edit_version_id);
    // Start with state assumptions, and change as necessary below
    $addNewJob        = true;
    $addNewJobVersion = true;
    $editJob          = false;
    $editJobVersion   = false;
    $useTemplate      = false;
    $jobVersionNum = 1;
    
    /////////////////////////////////////////
    //////// SETUP STATE ////////////////////
    
    // Add a new Job and JobVersion
    if($job_id === 'new') {      
    }
    // Add new JobVersion for an existing Job - but DON'T USE A PREV VERSION AS A TEMPLATE
    else if($template_version_id === 'new') {
      $addNewJob = false;      
    }
    // Add new JobVersion and USE A PREV VERSION AS A TEMPLATE
    else if($edit_version_id == null ) {
      $addNewJob   = false;
      $useTemplate = true;
    }
    
    // Edit a previous Job
    if($edit_job_id != null ) {
      $addNewJob        = false;
      $addNewJobVersion = false;
      $editJob          = true;
    }
    // Edit a previous JobVersion
    else if($edit_version_id != null ) {
      $addNewJob        = false;
      $addNewJobVersion = false;
      $editJobVersion   = true;
    }
    
    // TODO: test removing JobVersion comment and/or name when EDITING a Job Version.
       
    ////////////////////////////////////////
    /////// When saving new data ///////////
    if (!empty($this->data)) {
      //////////////////////////////////////////////////////////////////////////////////////////////////
      ///// Setup things before doing SaveAll(), such as removing blank Model fields from $data ////////
      
      if($addNewJob || $editJob) {
        $this->removeBlankFields(array('JobAltName' =>'name', 'Description'=>'content'), $editJob);
      }
      if($addNewJobVersion || $editJobVersion) {
        $this->removeBlankFields_assoc(array('JobVersionName' =>'name'), 
                                       'JobVersion',
                                       $editJobVersion);
        
        $this->removeBlankFields_assocHasMany(array('JobVersionComment'=>'comment'), 
                                              'JobVersion',  
                                              $editJobVersion);
      }
      
      /////////////////////////
      ///// Save All Data ///// // <editor-fold defaultstate="collapsed" desc="Saving data section">
      $this->Job->create(); // initializes a new Job Model for inserting into DB

      debug('Before trying any saves (but after removing blank optional fields), this->data is:');
      debug($this->data);
      // NOTE: Job->saveAll() is failing to insert 'job_id' into the JobVersion table, thus the transaction fails.
      // WORKAROUND: (1) Validate all data first using Job->saveAll (note param 'validate'=>'only'), 
      //             (2) Save the Job using Job->save().
      //             (3) Then use the Job's table row id to set related tables' job_id.
      //             (4) After that, do a saveAll() on each related table that has a 'job_id'. 
      
      // Validate all the data first (note 'validate'=>'only')
      if ($this->Job->saveAll($this->data, array('validate' => 'only'))) {

        // Save the Job data first so we can get its id...
        $retval = $this->Job->save($this->data, array('validate' => 'first'));
        if ($retval) {
          //debug("Supposedly the Job->save() worked.");  debug("retval was:");  debug($retval);

          unset($this->data['Job']); // Remove Job before doing a related Model's saveAll() so its not a dup 
          // Handle saving Tags (a 'hasAndBelongTo' relationship - emulated by using a 'join' table)
          $printDebugPr = false; // do I want func to print it's Pr() statements upon its errors
          $success = $this->saveJobDelimitedTags($this->data['Tag']['name'], $this->tagDelimiter, $printDebugPr);
          if (!$success) {
            debug("Something went wrong saving a Tag (either to the Tag table or to the 'join' table");
          }
          ///// SAVE RELATED TABLES (uses Job model's hasOne & hasMany associations) /////////
          ///// Sets related tables' foreign key 'job_id', then use the related Model's saveAll() 
          ///// Note that JobsTag was saved in saveJobDelimetedTags(), and won't be saved in this func
          /////  since there is no $data['JobsTag'] set.
          if ($this->Job->saveAllAssociated($this->data)) {
            $this->Session->setFlash(__('The job has been saved', true));
          }           
          else {
            debug('Job->saveAllAssociated() failed.');
            $this->Session->setFlash(__('Related models could not save. Please, try again.', true));
          }
          //$this->redirect(array('action' => 'index'));
        } // end if the Job saved
      }
      // If Job validate-only failed
      else {
        $this->Session->setFlash(__('The job didn\'t validate! Please, try again.', true));
      }
    } ///////// end  if(!empty($this->data)) /////////////////// </editor-fold>
        
    //////////////////////////////////////////////////////////////////////////////
    ////// When accessing new Add/Edit form (or form didn't validate) ////////////
		
    // Read any necessary data for the view
    
     // <editor-fold defaultstate="collapsed" desc="Get data for view">
    //   if (empty($this->data)) {

    if ($addNewJob) {
          }     else if ($addNewJobVersion && $useTemplate) {

      $job = $this->Job->read(null, $job_id);
      // only get 'data' if brand new form (don't overwrite 'data' if form didn't validate - keep user's entries for them)
      if (empty($this->data)) {
        // get data from the 'template' version
        $this->data = $this->Job->JobVersion->read(/* specific fields: */ null, $template_version_id);
      }
    }
    // If not using a previous Job Version as a template
    else if ($addNewJobVersion) {
      $job = $this->Job->read(null, $job_id);

    }     else if ($editJob) {
      // only get 'data' if brand new form (don't overwrite 'data' if form didn't validate - keep user's entries for them)
      if (empty($this->data)) {
        $this->Job->contain('Description', 'JobAltName', 'JobsTag', 'JobsTag.Tag');
        $this->data = $this->Job->find('first', array('conditions' => array('Job.id' => $edit_job_id)));

        // Get Tags into convenient format for view (single string of delimeter-separated tags).
        $tags = array();
        if (isset($this->data['JobsTag']) && !empty($this->data['JobsTag'])) {
          foreach ($this->data['JobsTag'] as $JobsTagIndex => $JobsTagArray) {
            $tags[] = $JobsTagArray['Tag']['name'];
          }
          $this->data['Tag']['name'] = implode($this->tagDelimiter . " ", $tags);
        }
      }
    }     else if ($editJobVersion) {
      // only get 'data' if brand new form (don't overwrite 'data' if form didn't validate - keep user's entries for them)
      if (empty($this->data)) {
        // TODO: test this
        $this->data = $this->Job->JobVersion->read(/* specific fields: */ null, $edit_version_id);
      }
    }
    //		}// </editor-fold>
    		
    
    // TODO: Make sure $versionNum gets set somewhere
    
    /*
    $job_id = 49;
    $template_version_id = 21;
    $edit_version_id = 13;
    */
    // testing
    //$addNewJob = true;
    //$job        = $this->Job->find('first', array('conditions'=>array('Job.id'=>15)));
    //$this->data = $this->Job->find('first', array('conditions'=>array('Job.id'=>15)));
    
    //$addNewJobVersion = false;
    // end testing
    
    // Get 'enum' table vals so the view's dropdowns get populated
    $statuses = $this->Job->JobVersion->Status->find('list');
		$authors  = $this->Job->JobVersion->Author->find('list');
		$jobTypes = $this->Job->JobVersion->JobType->find('list');
		$this->set(compact('statuses', 'authors', 'jobTypes'));
    
    // Prepulate the Version number with the incremented count
    $this->data['JobVersion']['version_num'] = 1;
    $this->data['JobVersion']['status_id'] = $this->Job->JobVersion->Status->defaultId;
    
    
    $this->set(compact(/*state vars:*/ 'addNewJob','addNewJobVersion','editJob','editJobVersion','versionNum', 
                       /*func params:*/'job_id', 'template_version_id', 'edit_job_id', 'edit_version_id',
                       /*job to be edited:*/  'job'));
   
    
  } /////////////////// end form() ///////////////////////
  
  
  /**
   * Removes empty OPTIONAL fields from the $data array, so that saveAll() won't even try to save to 
   * the associated model.  Its the API user's responsibility to ensure that the fields are optional.
   * 
   * @author Jason Frank
   * @param array $fields  The fields to check for emptiness - in the form 'Modelname' => 'fieldname'.  
   *                       If the field is empty, 'Modelname' will be unset from the $data array.
   * 
   * @param boolean $deleteBlankRecords  Should a blank field also be deleted from its database table? This
   *                                     is useful when a user is editing a form, and chooses to blank out
   *                                     an optional form field.
   *                                     If this param is true, a delete will be performed, using an 'id',
   *                                     such as: Job->Modelname->delete($this->data[Modelname]['id'].
   */
  function removeBlankFields($fields = array(), $deleteBlankRecords = false ) {
     
    foreach ($fields as $Modelname => $fieldname) {
      
      if( empty($this->data[$Modelname][$fieldname])) {
        
        // Also DELETE the database record if:
        //   (1) in edit mode and,
        //   (2) field is blank (the outer if catches that) and,
        //   (3) the edited record orignally HAD this optional table value to begin with - 
        //         a numeric id field is included if the record had an id to begin with 
        //        (an optional field had a value).
        if($deleteBlankRecords && is_numeric($this->data[$Modelname]['id']) ) { 
          
          if ($this->Job->$Modelname->delete($this->data[$Modelname]['id'])) {
            $this->Session->setFlash("$Modelname $fieldname deleted");
          }
          else {
            $this->Session->setFlash("$Modelname $fieldname NOT deleted successfully");
          }
        } // end if deleteBlankRecords
        
        unset ($this->data[$Modelname]); // now saveAll(this->data) won't try saving in $Modelname table
      } // end if field is empty
    } // end foreach
    
  } ////////////// end removeBlankFields() //////////////////
  
  
  
  /**
   * See comments for other versions of this func.
   * 
   * @param array   $fields
   * @param string  $AssocModel
   * @param boolean $deleteBlankRecords 
   */
  function removeBlankFields_assoc($fields = array(), $AssocModel, $deleteBlankRecords = false ) {
    
    foreach ($fields as $Modelname => $fieldname) {

    if( empty($this->data[$Modelname][$fieldname])) {

      // Also DELETE the database record if:
      //   (1) in edit mode and,
      //   (2) field is blank (the outer if catches that) and,
      //   (3) the edited record orignally HAD this optional table value to begin with - 
      //         a numeric id field is included if the record had an id to begin with 
      //        (an optional field had a value).
      if($deleteBlankRecords && is_numeric($this->data[$Modelname]['id']) ) { 

        if ($this->Job->$AssocModel->$Modelname->delete($this->data[$Modelname]['id'])) {
          $this->Session->setFlash("$Modelname $fieldname deleted");
        }
        else {
            $this->Session->setFlash("$Modelname $fieldname NOT deleted successfully");
        }
      } // end if deleteBlankRecords

      unset ($this->data[$Modelname]); // now saveAll(this->data) won't try saving in $Modelname table
      } // end if field is empty
    } // end foreach
    
  } /////////// end removeBlankFields_assoc() /////////////////////
  
  
  
  
/**
 * This version deals specifically with hasMany associations of a model associated with one that is 
 * directly associated with this model.  The param $AssocModel is used to get the model that we want to
 * delete a record from.   HasMany associations have their part of the data array
 * be indexed deeper.  This version iterates through all indices of the hasMany data.
 * 
 * Removes empty OPTIONAL fields from the $data array, so that saveAll() won't even try to save to 
 * the associated model.  Its the API user's responsibility to ensure that the fields are optional.
 * 
 * @author Jason Frank
 * @param array $fields  The fields to check for emptiness - in the form 'Modelname' => 'fieldname'.  
 *                       If the field is empty, 'Modelname' will be unset from the $data array.
 * 
 * @param string $AssocModel   Name of the model that is directly associated with this model.  It is needed
 *                             to delete (it uses this AssocModel as a bridge to get to the other model).
 * 
 * @param boolean $deleteBlankRecords  Should a blank field also be deleted from its database table? This
 *                                     is useful when a user is editing a form, and chooses to blank out
 *                                     an optional form field.
 *                                     If this param is true, a delete will be performed, using an 'id',
 *                                     such as: Job->Modelname->delete($this->data[Modelname]['id'].
 */
  function removeBlankFields_assocHasMany($fields = array(), $AssocModel, $deleteBlankRecords = false ) {
    
    foreach ($fields as $Modelname => $fieldname) {
      foreach($this->data[$Modelname] as $hasManyIndex => $array) {
      
        if( empty($this->data[$Modelname][$hasManyIndex][$fieldname])) {

          // Also DELETE the database record if:
          //   (1) in edit mode and,
          //   (2) field is blank (the outer if catches that) and,
          //   (3) the edited record orignally HAD this optional table value to begin with - 
          //         a numeric id field is included if the record had an id to begin with 
          //        (an optional field had a value).
          if($deleteBlankRecords && is_numeric($this->data[$Modelname][$hasManyIndex]['id']) ) { 

            if ($this->Job->$AssocModel->$Modelname->delete($this->data[$Modelname][$hasManyIndex]['id'])) {
              $this->Session->setFlash("$Modelname $fieldname deleted");
            }
            else {
              $this->Session->setFlash("$Modelname $fieldname NOT deleted successfully");
            }
          } // end if deleteBlankRecords

          unset ($this->data[$Modelname][$hasManyIndex]); // now saveAll(this->data) won't try saving in $Modelname table
        } // end if field is empty
      }
    } // end outer foreach
    
    if( empty($this->data[$Modelname] )) {
      unset ($this->data[$Modelname]); // now saveAll(this->data) won't try saving in $Modelname table
    }
    
  } ////////////// end removeBlankFields_hasMany() //////////////////
  
  /**
   * Note that this function relies on the Job->id referring to the desired job.
   * 
   * @author Jason Frank 8/4/2011
   * @param string $tagStr
   * @param string $tagDelimiter 
   * @param boolean $printDebugPr  Do you want this method to print its Pr() debug msgs upon errors?
   */
  function saveJobDelimitedTags($tagStr, $tagDelimiter, $printDebugPr = false) {

    // Get a list of tags that were associated with the current Job before it was edited
    // We'll use this list to mark off which tags have been retained by the edit,
    // so that we know which ones to delete from the 'join' table.
    $this->Job->JobsTag->contain('Tag');
    $oldJobTagList = $this->Job->JobsTag->find('all', array('conditions'=>
                                                             array('JobsTag.job_id' => $this->Job->id)));
    $oldJobTagIdList = array();
    // flatten out the array so we have just key=>val as: tag_name=>tag_id
    foreach ($oldJobTagList as $index => $JobsTag_Tag_Array) {
      $tagName = $JobsTag_Tag_Array['Tag']['name'];
      $oldJobTagIdList[$tagName] = $JobsTag_Tag_Array['Tag']['id'];
    }
    //debug("oldJobTagIdList:"); debug($oldJobTagIdList);
    
    $tags = explode( $tagDelimiter, $tagStr);
    
    foreach($tags as $_tag) {
      // clean up the suppossed tag (it could be whitespace)
      $_tag = trim($_tag);

      // only work with valid, non-blank tags (after being cleaned up)
      if ($_tag) { 
                 //pr("--------------------------- tag: $_tag"); //pr($_tag);

        // Try to find existing tag like this one in the Tag table
        $this->Job->JobsTag->Tag->recursive = -1;
        $tag = $this->Job->JobsTag->Tag->find('first', array('conditions'=>array('name'=>$_tag)));

        // If no matching tag found in database table, save this new one.
        if (!$tag) {
          $this->Job->JobsTag->Tag->create(); // must init new model for saving since loop
          // SAVE THE TAG in Tag table
          $tag = $this->Job->JobsTag->Tag->save(array('name'=>$_tag));
          // save the id
          if($tag !== false) {
            $tag['Tag']['id'] = $this->Job->JobsTag->Tag->id;  //pr("Tag saved: $tag"); //pr($tag);
          }
          else if(!$tag) {
            if($printDebugPr) pr("Tag NOT saved: $_tag"); 
            return false;
          }
        }   
        // Prepare for saving a record in the join table
        $findConditions = array('conditions' => array('JobsTag.job_id'=>$this->Job->id));
        $joinTableJobMatches = $this->Job->JobsTag->find('all', $findConditions );
        $findConditions = array('conditions' => array('JobsTag.job_id'=>$this->Job->id,
                                                      'JobsTag.tag_id'=>$tag['Tag']['id']));      
        $joinTableJobAndTagMatches = $this->Job->JobsTag->find('all', $findConditions );

        // SAVE RECORD TO JOIN TABLE, if the job_id/tag_id pair is not in the join table yet
        if(! count($joinTableJobAndTagMatches)) {
          $this->Job->JobsTag->create(); // must init new model for saving or next iter would replace prev iter's saved record
          $retval = $this->Job->JobsTag->save(array('job_id'=>$this->Job->id,
                                                    'tag_id'=>$tag['Tag']['id']));
          if($retval) { //pr("Record in Join Table saved. job_id: {$this->Job->id}, tag_id: {$tag['Tag']['id']}");
          }
          else {  
            if($printDebugPr) debug('Record in JobsTags Join Table NOT successfully saved.');   
            return false;
          }
        }
        // If this tag matches one that this Job had before it was edited, remove it from this list
        // (any leftover tags in this list will then be removed from the 'join' table below)
        if( isset($oldJobTagIdList[$_tag]) ) {
          unset($oldJobTagIdList[$_tag]);
        }
      } ///// end if we have a valid tag ////////////
    } /// end foreach tag ///////////////
    
    // Delete from the 'join' table any tags that the Job originally had, but have been removed by the user
    // Only 'leftover' tags should remain in this list at this point
    foreach ($oldJobTagIdList as $tagName => $tagId) {
      $conditions = array('JobsTag.tag_id' => $tagId, 'JobsTag.job_id' => $this->Job->id);
      // Delete from 'join' table
      if($this->Job->JobsTag->deleteAll($conditions)) {     }
      else {        debug("JobsTag record FAILED to be successfully deleted");      }
    }
    
    return true; // indicate success
  } /////////////// end saveJobDelimitedTags() ///////////////////
  
  
  
  /**
   * DELETE
   */
	function delete($id = null) {
    
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for job', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Job->delete($id)) {
      
			$this->Session->setFlash(__('Job deleted', true));
			$this->redirect(array('action'=>'index'));
		}
    
		$this->Session->setFlash(__('Job was not deleted', true));
		$this->redirect(array('action' => 'index'));
	} ////////////////////// end delete() //////////////////
} ///////////////////////////////// end class //////////////////////
